package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.Tag;
import com.mhl.entity.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

//    private ArrayList<Product> userProvideList;
//    private ArrayList<Product> userStarList;
//    private ArrayList<Product> userOrderList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Button to_register = findViewById(R.id.to_register);
        ImageButton login = findViewById(R.id.login);


        to_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = ((EditText) findViewById(R.id.account_text)).getText().toString().trim();
                String password = ((EditText) findViewById(R.id.password_text)).getText().toString().trim();

                Login(username,password);
            }
        });



    }


    private void Login(String username,String password)
    {
        if (username.equals("") || password.equals(""))
            Toast.makeText(LoginActivity.this, "username and password can't be empty", Toast.LENGTH_SHORT).show();
        else {
            //此处可以加与服务器相关工作、判定
            JSONObject jsonParam = new JSONObject();
            try {
                jsonParam.put("username", username);
                jsonParam.put("password", password);
                String json = jsonParam.toString();
                MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

                OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp()+"login", requestBody, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String data = response.body().string();
                        int state = 1;

                        try {
                            JSONObject userJson = new JSONObject(data);
                            state = userJson.getInt("errcode");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Looper.prepare();

                        if(state == 2){
                            Toast.makeText(LoginActivity.this, "Can't find this user", Toast.LENGTH_SHORT).show();
                        }
                        else if(state == 1){
                            Toast.makeText(LoginActivity.this, "Wrong password", Toast.LENGTH_SHORT).show();
                        }
                        else{
                            User.getInstance().getUserLike().clear();
                            LocalData.getInstance().TagList.clear();

                            try {
                                JSONObject userJson = new JSONObject(data);
                                JSONObject userInfo = userJson.getJSONObject("data");
                                JSONArray userLike = userInfo.getJSONArray("user_like");
                                User.setUsername(userInfo.getString("username"));
                                //后端要加
                                //User.setUserNickname(userInfo.getString("nickname"));
                                User.setUserPassword(userInfo.getString("password"));
                                User.setUserId(userInfo.getInt("id"));
                                User.setUserGender(userInfo.getInt("gender"));
                                User.setUserDescription(userInfo.getString("description"));
                                for (int i = 0; i < userLike.length(); i++) {
                                    User.getUserLike().add(userLike.getInt(i));
                                }

                                //System.out.println("in login User user id is: " + User.getUserId());

                                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                                startActivity(intent);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                        Looper.loop();
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }
}





//                            try {
//                                    JSONObject userJson = new JSONObject(data);
//                                    JSONObject userInfo = userJson.getJSONObject("data");
//
//                                    User.setUsername(userInfo.getString("username"));
//                                    User.setUserPassword(userInfo.getString("password"));
//                                    User.setUserId(userInfo.getString("id"));
//                                    User.setUserGender(userInfo.getString("gender"));
//                                    User.setUserDescription(userInfo.getString("description"));
//
//                                    JSONObject jsonParam = new JSONObject();
//                                    jsonParam.put("id",User.getInstance().getUserId());
//                                    String json = jsonParam.toString();
//                                    MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
//                                    RequestBody requestBody = RequestBody.Companion.create(json, mediaType);
//                                    //todo fill true ip
//                                    OkHttpUtils.sendOkHttpResponse("", requestBody, new Callback() {
//@Override
//public void onFailure(@NonNull Call call, @NonNull IOException e) {
//        System.out.println(e);
//        }
//
//@Override
//public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//final String data = response.body().string();
//
//        try {
//        JSONObject userProductInfoJSON = new JSONObject(data);
//        JSONArray userProvideListJSON = userProductInfoJSON.getJSONArray("userProvide");
//        JSONArray userOrderListJSON = userProductInfoJSON.getJSONArray("userOrder");
//        JSONArray userStarListJSON = userProductInfoJSON.getJSONArray("userStar");
//
//        for (int i = 0; i < userProvideListJSON.length(); i++) {
//        JSONObject item = userProvideListJSON.getJSONObject(i);
//        Product product = new Product();
//        product.setPrice(item.getString("price"));
//        product.setName(item.getString("name"));
//        product.setURL(item.getString("url"));
//        product.setImageId(item.getInt("imgId"));
//        product.setId(item.getString("id"));
//        userProvideList.add(product);
//        }
//
//        for (int i = 0; i < userOrderListJSON.length(); i++) {
//        JSONObject item = userOrderListJSON.getJSONObject(i);
//        Product product = new Product();
//        product.setPrice(item.getString("price"));
//        product.setName(item.getString("name"));
//        product.setURL(item.getString("url"));
//        product.setImageId(item.getInt("imgId"));
//        product.setId(item.getString("id"));
//        userOrderList.add(product);
//        }
//
//        for (int i = 0; i < userStarListJSON.length(); i++) {
//        JSONObject item = userStarListJSON.getJSONObject(i);
//        Product product = new Product();
//        product.setPrice(item.getString("price"));
//        product.setName(item.getString("name"));
//        product.setURL(item.getString("url"));
//        product.setImageId(item.getInt("imgId"));
//        product.setId(item.getString("id"));
//        userStarList.add(product);
//        }
//
//        User.setUserProvideList(userProvideList);
//        User.setUserOrderList(userOrderList);
//        User.setUserStarList(userStarList);
//
//        } catch (JSONException e) {
//        e.printStackTrace();
//        }
//
//        }
//        });
//
//        }catch (JSONException e){e.printStackTrace();}